package com.ashlikun.glideutils

import android.graphics.drawable.Drawable
import com.ashlikun.glideutils.GlideUtils.getImageView
import com.ashlikun.glideutils.GlideUtils.resetScaleType
import com.ashlikun.glideutils.GlideUtils.setErrorScaleType
import com.ashlikun.glideutils.okhttp.ProgressListener
import com.ashlikun.glideutils.okhttp.ProgressManage
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target

/**
 * 作者　　: 李坤
 * 创建时间: 2024/8/2　18:33
 * 邮箱　　：496546144@qq.com
 *
 *
 * 功能介绍：
 */
internal class ProgressRequestListener(isSetScaleType: Boolean, path: Any?, progressListener: ProgressListener?) : RequestListener<Drawable> {
    var isSetScaleType = false
    var path: Any?
    var progressListener: ProgressListener? = null

    init {
        this.isSetScaleType = isSetScaleType
        this.path = path
        this.progressListener = progressListener
    }

    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>, isFirstResource: Boolean): Boolean {
        //设置加载失败图为
        setErrorScaleType(getImageView(target), isSetScaleType)
        if (progressListener != null) {
            progressListener!!.onProgress(ProgressManage.getTotalBytesRead(path), ProgressManage.getContentLength(path), true)
            ProgressManage.remove(path)
        }
        return false
    }

    override fun onResourceReady(resource: Drawable, model: Any, target: Target<Drawable>, dataSource: DataSource, isFirstResource: Boolean): Boolean {
        //还原图片缩放类型
        resetScaleType(getImageView(target), isSetScaleType)
        if (progressListener != null) {
            progressListener!!.onProgress(ProgressManage.getTotalBytesRead(path), ProgressManage.getContentLength(path), true)
            ProgressManage.remove(path)
        }
        return false
    }
}
